/**
 * middleware loader
 * @params app koa实例
 * 加载所以 middleware 可通过 'app.middleware.${目录}.${文件}‘ 访问
 * 例子
 *   app/midddleware
 *     |
 *     |-- json-webtoken
 *             |
 *             |-- demo.js
 * 
 * => app.middleware.jsonWebtoken.demo
 */

const { globSync } = require("glob");
const path = require("path");
const { sep } = path


module.exports = (app) => {
    // 读取app/middleware/**/**.js 下面所有文件
    const middlewarePath = path.resolve(app.businessPath, `middleware`);

    const fileList = globSync(path.resolve(middlewarePath, '**/*.js'), {
        absolute: true,  // 这个选项确保返回绝对路径
        windowsPathsNoEscape: true,//
    })

    // 遍历文件，把内容加载到 app.middleware下
    const middleware = {}

    fileList.forEach(file => {
        let name = path.resolve(file)
        // 截取路径
        name = name.substring(name.lastIndexOf(`middleware${sep}`) + `middleware${sep}`.length, name.lastIndexOf('.'));
        // 把'-_',改成驼峰命名
        name = name.replace(/[_-][a-z]/ig, (s) => s.substring(1).toUpperCase())

        // 挂在到 middleweare 到app对象中
        let tmp = middleware
        let names = name.split(sep)

        for (let i = 0; i < names.length; i++) {
            if (i == names.length - 1) {
                // 目录的最后文件
                tmp[names[i]] = require(path.resolve(file))(app)
            } else {
                // 文件夹
                if (!tmp[names[i]]) {
                    tmp[names[i]] = {}
                    tmp = tmp[names[i]]
                }

            }
        }
    })

    app.middlewares = middleware

}